module.exports = app => {
  const express = require('express')
  const router = express.Router()
  const AdminUser = require('../../models/AdminUser')
  const jwt = require('jsonwebtoken')
  const assert = require('http-assert')
  const MAO = require('multer-aliyun-oss')

  const authMiddleware = require('../../middleware/auth')

  const resourceMiddleware = require('../../middleware/resource')
  const Ad = require('./Ad')
  const Article = require('./Article')
  const Category = require('./Category')
  const Hero = require('./Hero')
  const Item = require('./Item')

  const routerMap = {
    Ad,
    AdminUser,
    Article,
    Category,
    Hero,
    Item,
  }

  router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  })
  //查找所有
  router.get('/', async (req, res) => {
    let queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }
    if (req.Model.modelName === 'Article') {
      queryOptions.populate = 'categories'
    }
    const items = await req.Model.find().setOptions(queryOptions)
    res.send(items)
  })
  //查找
  router.get('/:id', async (req, res) => {
    const model = await req.Model.findById(req.params.id)
    res.send(model)
  })
  //编辑
  router.put('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
  })
  //删除
  router.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id)
    res.send({
      success: true
    })
  })

  /**
 * This function comment is parsed by doctrine
 * asdasdasdasdasd
 * @route POST /users
 * @param {Point.model} point.body.required - the new point
 * @group OAuto - 用户登录验证
 * @param {string} email.query.required - username or email
 * @param {string} password.query.required - user's password.
 * @param {enum} status.query.required - Status values that need to be considered for filter - eg: available,pending
 * @operationId retrieveFooInfo
 * @produces application/json application/xml
 * @consumes application/json application/xml
 * @returns {Response.model} 200 - An array of user info
 * @returns {Product.model}  default - Unexpected error
 * @returns {Array.<Point>} Point - Some description for point
 * @headers {integer} 200.X-Rate-Limit - calls per hour allowed by the user
 * @headers {string} 200.X-Expires-After - 	date in UTC when token expires
 * @security JWT
 * @security XAUTH
 */
  app.post('/admin/api/rest/login', async (req, res) => {

    const { userName, password } = req.body
    const user = await AdminUser.findOne({ userName }).select('+password')
    assert(user, 422, "用户不存在")
    if (!user) {
      return res.status(422).send({
        message: "用户不存在"
      })
    }
    //密码校验
    const isValid = require('bcrypt').compareSync(password, user.password)
    assert(isValid, 422, "用户名或者密码错误")

    const token = jwt.sign({ id: user._id }, app.get('secret'))
    res.send({ token })
  })

  app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(), router)

  const multer = require('multer')
  // const upload = multer({ dest: __dirname + '/../../uploads' })
  const upload = multer({
    storage: MAO({
        config: {
            region: 'oss-accelerate',
            accessKeyId: 'LTAI4FkijuixnUHtpPGTLo9f',
            accessKeySecret: 'yT3Uo0WIxuXJYGTGxH1EuFedTBbpFu',
            bucket: 'vue-node'
        }
    })
});

  app.post('/admin/api/uploads', authMiddleware(), upload.single('file'), async (req, res) => {
    const file = req.file
    // file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
  })

  // app.use(async (err, req, res, next) => {
  //   res.status(err.statusCode || 500).send({
  //     message: err.message
  //   })
  // })
}